package cn.fjc920.siaa.fragments

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import cn.fjc920.siaa.R
import cn.fjc920.siaa.activitys.HomePageActivity
import cn.fjc920.siaa.adapters.HoursAdapter
import cn.fjc920.siaa.base.Strings
import cn.fjc920.siaa.internetUtils.OkhttpUtils
import cn.fjc920.siaa.itembean.Hours
import com.google.android.material.floatingactionbutton.FloatingActionButton
import kotlinx.android.synthetic.main.home_all_fragment.*
import kotlinx.android.synthetic.main.home_all_fragment.view.*
import okhttp3.Request
import org.jsoup.Jsoup
import java.io.IOException
import kotlin.properties.Delegates

class HomeAllFragment : Fragment() {

    private var isHide by Delegates.notNull<Boolean>()
    private lateinit var goto_top: FloatingActionButton
    private lateinit var tv_Record: TextView
    private lateinit var tv_Total_pages: TextView
    private lateinit var tv_current_page: TextView
    private var record = 0
    private var total_page = 0
    private var current_page = 0
    private lateinit var homePageActivity: HomePageActivity
    private var adapter: HoursAdapter? = null
    private lateinit var nextUrl: String
    private val url = "${OkhttpUtils.url}item/mine"
    private var page = 2
    private lateinit var rfr: SwipeRefreshLayout

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val activity = activity as HomePageActivity
        val view = inflater.inflate(R.layout.home_all_fragment, container, false)
        init(view,activity)
        return view
    }

    private fun init(view: View,activity: HomePageActivity) {

        activity.getSharedPreferences("cn.fjc920.siaa_preferences",Context.MODE_PRIVATE).apply {
            isHide = getBoolean("hide_user",true)
        }

        goto_top = view.btn_goto_top
        rfr = view.all_refresh
        tv_Record = view.tv_Record
        tv_Total_pages = view.tv_Total_pages
        tv_current_page = view.tv_current_page
        homePageActivity = activity

        initList(url,false, isRefresh = false)
        initRefresh(view)
        initGotoTop()
    }

    private fun initGotoTop(){
        goto_top.setOnClickListener {
            all_recyclerview.scrollToPosition(0)
        }
    }

    private fun initRefresh(view: View) {

        view.all_refresh.setColorSchemeResources(R.color.purple_500)
        view.all_refresh.setOnRefreshListener {
           refresh()
        }
    }

    fun refresh() {
        record = 0
        current_page = 0
        total_page = 0
        page = 2
        initList(url,true, isRefresh = true)
    }

    private fun initList(url: String,clearAdapterData:Boolean,isRefresh:Boolean) {

        val hoursList = ArrayList<Hours>()

        OkhttpUtils.getAsync(url, object : OkhttpUtils.DataCallBack {
            override fun requestFailure(request: Request?, e: IOException?) {
                if (rfr.isRefreshing) {
                    rfr.isRefreshing = false
                    rfr.announceForAccessibility("刷新失败，请检查网络！")
                }
            }
            @SuppressLint("SetTextI18n")
            override fun requestSuccess(result: String) {

                val doc = Jsoup.parse(result)

                //获取总共页数
                val hoursData = doc.select("div[class=pagination col-md-8] div").first()!!.text()
                current_page =
                    hoursData.substring(hoursData.indexOf("第") + 1, hoursData.indexOf("页")).toInt()
                tv_current_page.text = "${current_page}页"

                if (total_page <= 0) {
                    total_page = hoursData.substring(
                        hoursData.indexOf("共") + 1,
                        hoursData.lastIndexOf("页")
                    ).toInt()
                    tv_Total_pages.text = "${total_page}页"
                }

                if (record <= 0){
                    record = hoursData.substring(
                        hoursData.indexOf("计")+1,
                        hoursData.indexOf("条")
                    ).toInt()
                    tv_Record.text = "${record}条"
                }

                //获取下一页链接
                nextUrl = "${OkhttpUtils.url}item/mine?page=${page}"
                page++


                val elements = doc.select("tbody tr")
                for (element in elements) {

                    //获取用户
                    val user = element.child(0).text()
                    //获取部门
                    val door = element.child(1).text()
                    //获取日期
                    val date = element.child(2).text()
                    //获取项目
                    val project = element.child(3).text()
                    //获取类型
                    val type = element.child(4).text()
                    //获取时长
                    val time = element.child(5).text()
                    //获取备注
                    val remarks = element.child(6).text()

                    //获取编辑链接
                    val editUrl = "${OkhttpUtils.url}${element.child(7).child(0).attr("href").substring(1)}"

                    //获取_csrf
                    val inputs = element.child(7).child(1).select("input[type=hidden]")
                    val input = inputs[0]
                    val _csrf = input.attr("value")

                    //获取工时id
                    val input1 = inputs[1]
                    val hoursId = input1.attr("value")

                    //获取删除Url
                    val deleteUrl = "${OkhttpUtils.url}item/delete"

                    hoursList.add(Hours(user, door, date, project, type, time, remarks,editUrl,deleteUrl,_csrf,hoursId))
                }

                if (adapter == null) {
                    initAdapter(hoursList)
                } else {
                    if (clearAdapterData) {
                        adapter!!.clearData()
                    }
                    adapter!!.loadMore(hoursList,isRefresh)
                }
                if (rfr.isRefreshing) {
                    rfr.isRefreshing = false
                    rfr.announceForAccessibility("刷新成功")
                }
            }
        })
    }

    private fun initAdapter(hoursList: ArrayList<Hours>) {

        val layoutManager = LinearLayoutManager(homePageActivity)
        all_recyclerview.layoutManager = layoutManager

        adapter = HoursAdapter(hoursList,isHide)
        all_recyclerview.adapter = adapter

        //上拉加载更多
        all_recyclerview.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            val lm = all_recyclerview.layoutManager as LinearLayoutManager?
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                val totalItemCount = recyclerView.adapter!!.itemCount
                val lastVisibleItemPosition = lm!!.findLastVisibleItemPosition()
                val visibleItemCount = recyclerView.childCount
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItemPosition == totalItemCount - 1 && visibleItemCount > 0) {
                    if (current_page != total_page) {
                        //加载更多
                        initList(nextUrl,false, isRefresh = false)
                    }else{
                        Toast.makeText(context,"我是有底线的！",Toast.LENGTH_SHORT).show()
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //获取RecyclerView当前顶部显示的第一个条目对应的索引
                val position = lm!!.findFirstVisibleItemPosition()
                //根据索引来获取对应的itemView
                val firstVisiableChildView = lm.findViewByPosition(position)
                //获取当前显示条目的高度
                val itemHeight = firstVisiableChildView!!.height
                //获取当前Recyclerview 偏移量
                val flag = position * itemHeight - firstVisiableChildView.top
                //注意事项：recyclerView不要设置padding
                if(flag==0)
                    goto_top.hide()
                else
                    goto_top.show()
            }
        })
    }
}
